package com.jml.dubbo.server.handler;

import java.lang.reflect.Method;
import java.util.Map;

import com.jml.dubbo.server.req.RpcRequest;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;


public class DubboServerHandler extends ChannelInboundHandlerAdapter {
    private Map<String, Object> hanlderMap;
    
    public DubboServerHandler(Map<String, Object> hanlderMap) {
        this.hanlderMap = hanlderMap;
    }

    /**
     * 服务器监听我们的客户端发送消息
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 获取参数对象
        RpcRequest rpcRequest = (RpcRequest) msg;
        System.out.println("服务器端获取到消息:" + msg.toString());
        // 直接采用反射机制执行我们实现实现类的方法
        if (rpcRequest == null) {
            return;
        }
        String serviceName = rpcRequest.getClassName();
        Object objectImpl = hanlderMap.get(serviceName);
        if (objectImpl == null) {
            return;
        }
        // 使用反射机制执行我们的目标方法
        Method method = objectImpl.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        Object result = method.invoke(objectImpl, rpcRequest.getParamsValue());
        // 返回结果
        System.out.println("服务器响应给客户端:" + result);
        ctx.writeAndFlush(result);
    }
}
